<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import Editor from './Editor.vue'
// import useEditorTool from '@/plugins/stratocirri-plus/hooks/useEditorTool'

interface Props {
  data?: Record<string, any> | never | null
  status: string
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = reactive<Record<string, any>>({
  // content: '<p>dfsadfasdf12431243</p'
  content: ''
})

// const { formatImage } = useEditorTool()

const rules = reactive<FormRules>({
  content: [{ required: true, message: '名称不能为空!', trigger: 'change' }]
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      form[key] = props.data![key]
    })
  }
}

const formatImage = (html: any) => {
  // html = '<img src="image1.jpg" data-a="aa"><img src="image22.jpg" data-a="a2a"><p>Some text with no image</p><img width="500px" src="i23mage3.jpg"  1  >'
  const regex = /(<img.*?src=")(.*?)(".*?>)/g
  const matches = html.match(regex)

  matches.forEach((v: any) => {
    if (v.indexOf('width') < 0) {
      html = html.replace(v, v.replace('img', "img style='width: 100%;'"))
    }
  })

  return html
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form).forEach((key: string) => {
    if (key === 'content') {
      result[key] = formatImage(form[key])
    } else {
      result[key] = form[key]
    }
  })
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="base-form">
      <el-form-item label="内容：" prop="content" style="width: 100%">
        <Editor v-model="form.content" />
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.base-form {
  width: 100%;
  @include flex(row, flex-start, center);
  flex-wrap: wrap;
  .el-form-item {
    // width: 50%;
    padding-right: 50px;
    box-sizing: border-box;
  }
}
</style>
